package com.example.springbootsecurity.security;

import com.example.springbootsecurity.entity.ShiroRole;
import com.example.springbootsecurity.entity.ShiroUser;
import com.example.springbootsecurity.service.ShiroMenuService;
import com.example.springbootsecurity.service.ShiroRoleService;
import com.example.springbootsecurity.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private ShiroUserService userService;

    @Autowired
    private ShiroRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //这里通过username（登录时输入的用户名）获取到用户信息
        ShiroUser userInfo = userService.getUserByName(username);
        List<GrantedAuthority> authorities = new ArrayList<>();

        if (userInfo != null) {
            //查询用户角色
            List<ShiroRole> list = roleService.getUserRole(username);
            if (list != null && list.size() > 0) {
                //定义用户权限
                for (ShiroRole role : list) {
                    authorities.add(new SimpleGrantedAuthority("ROLE_" +role.getRoleName()));
                }
            }
        }
        //由于权限参数不能为空，所以这里先使用AuthorityUtils.commaSeparatedStringToAuthorityList方法模拟一个admin的权限，该方法可以将逗号分隔的字符串转换为权限集合。
        //数据库中的密码是加密后的
        //AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_admin")
        return new User(username, userInfo.getPassWord(), authorities);
    }

}
